<template>
  <div id="app" ref="yarnCheckRef" tabindex="0" class="yarn-check">
    <van-nav-bar left-arrow title="纱线盘库" @click-left="comeBack" left-text="返回">
    </van-nav-bar>

    <!-- 历史查询 -->
    <van-search v-model="queryParam.queryParam" @search="filterDataFn(5, 100)"></van-search>

    <!-- 主表单 -->
    <van-form validate-first validate-trigger="onSubmit" @submit="confirmCheckFn">
      <van-field label="纱线名称" colon clearable placeholder="请输入纱线名称" v-model="checkData.name"></van-field>
      <van-field label="纱线编号" colon clearable placeholder="请输入纱线编号" v-model="checkData.no" :rules="[{ validator: validatorFn, message: '请输入纱线编号' }]" @input="checkData.yarnId = 0">
        <template #button>
          <van-button type="info" native-type="button" size="small" @click="filterDataFn(1, 100)">筛选核对</van-button>
        </template>
      </van-field>
      <van-field label="颜色" colon clearable placeholder="请输入颜色" v-model="checkData.colorName" :rules="[{ validator: validatorFn, message: '请输入颜色' }]">
        <template #button>
          <van-button type="info" native-type="button" size="small" @click="filterDataFn(2, 100)">筛选</van-button>
        </template>
      </van-field>
      <van-field label="支数" colon clearable readonly v-model="checkData.standard"></van-field>
      <van-field label="批次" colon clearable placeholder="请输入生产批次" v-model="checkData.lotNum" :rules="[{ validator: validatorFn, message: '请输入批次' }]" @input="checkData.batchId = 0">
        <template #button>
          <van-button type="info" native-type="button" size="small" @click="filterDataFn(3, 100)">筛选</van-button>
        </template>
      </van-field>
      <van-field label="区域" colon clearable readonly placeholder="请输入区域" v-model="checkData.stockArea" @focus="() => filterDataFn(4, 100)"></van-field>
      <van-field label="库存标重" type="tel" colon clearable placeholder="请输入库存标重" :rules="[{ validator: validatorFn, message: '请输入标重' }]" v-model="checkData.stock"></van-field>
      <van-field label="库存包数" type="tel" colon clearable placeholder="请输入库存包数" v-model="checkData.packNum" ></van-field>
      <van-field label-width="25vw" label="批次预计库存" type="tel" colon clearable placeholder="请输入预计库存" v-model="checkData.expectStock" ></van-field>
      <van-field label-width="25vw" label="批次预计出库" type="tel" colon clearable placeholder="请输入预计出库" v-model="checkData.expectOutTotal" ></van-field>
      <van-field label="实际回潮" type="tel" colon clearable placeholder="请输入实际回潮" :rules="[{ validator: validatorFn, message: '请输入实际回潮' }]" v-model="checkData.actMoistureRegain" ></van-field>
      <van-field label="打印张数" type="tel" colon clearable placeholder="请输入打印张数" v-model="printCount" ></van-field>
      <div style="margin: 16px;display: flex;justify-content: center;width: 90%;">
        <van-button block type="info" native-type="submit">确认并打印</van-button>
        <div style="flex: 0 0 4vw;"></div>
        <van-button block type="warning" native-type="button" @click="rePrintFn">再次打印</van-button>
      </div>
    </van-form>

    <!-- 弹出面板 -->
    <van-action-sheet v-model="showActionSheet" :actions="actionSheetData" title="请选择" cancel-text="取消" close-on-click-action get-container="#app" @cancel="showActionSheet = false" @select="selectFilterDataFn"></van-action-sheet>
  </div>
</template>

<script>
import {comeBack, openWin} from "@/utils";
import {getInfo, getMacAddress} from "@/utils/auth";
import dayjs from "dayjs";
import {
  analyseYarnNo,
  confirmYarnCheck, filterYarnCheckData,
  filterYarnColor,
  getByType,
  getYarnStandardFilter,
  listYarnBatchByYarn
} from "@/api/yarn";
import {SPLIT_COMMA, SPLIT_XG, SPLIT_XHX, SPLIT_YKH, SPLIT_ZKH} from "@/api/enum";

export default {
  name: "yarn-check",
  data() {
    return {
      /* 查询相关 */
      queryParam: {
        yarnNo: "",
        pageNum: 1,
        pageSize: 6,
        optFlag: 1, //1-纱线; 2-颜色; 3-批次; 4-区域; 5-历史盘库记录
      },
      queryTimer: null,
      showActionSheet: false,
      actionSheetData: [],

      /* 打印相关 */
      printCount: 1,
      printStatus: false,
      connectionStatus: false,

      /* 盘库数据 */
      checkData: {
        id: 0,
        name: "",
        yarnId: 0,
        no: "",
        colorName: "",
        standard: "",
        batchId: 0,
        lotNum: "",
        stockArea: "",
        stock: "",
        packNum: "",
        expectStock: "",
        expectOutTotal: "",
        actMoistureRegain: "",
        checkerName: "",
      }
    }
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      that.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }

    // that.initFn(that);   //dev fixme
  },
  methods: {
    comeBack,

    /* 初始化 */
    initFn() {
      const that = this;
      if (getMacAddress()) {
        that.isEnabledBluetooth();
      } else {
        that.$toast.fail('如需打印，请退出登录选择打印机')
      }
      window.api.addEventListener({
        name:'viewdisappear'
      }, function() {
        window.api.closeWin();
      });
    },

    /* 核对纱线编号 */
    analyseYarnNoFn() {
      const that = this;
      clearTimeout(that.queryTimer);
      analyseYarnNo({
        no: that.checkData.no,
        color: that.checkData.colorName,
      }, data => {
        that.checkData.colorName = data.colorName;
        that.checkData.standard = parseFloat(data.standard) + SPLIT_XG + data.strandNum;
      });
    },

    /* 重置盘库数据 */
    resetCheckData(optFlag) {
      const that = this;
      if(optFlag < 4) {
        that.checkData.batchId = 0;
        if(optFlag < 2) {
          that.checkData.yarnId = 0;
          that.checkData.standard = "";
        }
      }
    },

    /* 筛选数据 */
    filterDataFn(optFlag, timer) {
      const that = this;
      that.queryParam.optFlag = optFlag;
      that.resetCheckData(optFlag);
      clearTimeout(that.queryTimer);
      that.queryTimer = setTimeout(() => {
        that.$refs.yarnCheckRef.focus();
        that.actionSheetData.splice(0, that.actionSheetData.length);
        if (1 == optFlag) {
          that.filterYarnStandardFn();
        } else if (2 == optFlag) {
          that.filterYarnColorFn();
        } else if (3 == optFlag) {
          that.filterYarnBatchFn();
        } else if (4 == optFlag) {
          that.filterYarnStoreAreaFn();
        } else if (5 == optFlag) {
          that.filterYarnCheckFn();
        }
      }, timer? timer : 2000);
    },

    /* 筛选纱线 */
    filterYarnStandardFn() {
      const that = this;
      getYarnStandardFilter({
        standard: that.checkData.no
      }, res => {
        if (res.code == 4000) {
          that.$toast.fail({
            message: "请重新登陆",
            onClose: () => {
              openWin("index");
            }
          });
        } else if (res.code) {
          that.$toast.fail({
            message: "新纱号即将核对颜色,务必填写完整",
            onClose: that.analyseYarnNoFn
          });
        } else {
          res.forEach(yarn => {
            that.actionSheetData.push({
              name: yarn.no,
              item: yarn
            });
          });
          that.showActionSheet = true;
        }
      });
    },
    /* 筛选颜色 */
    filterYarnColorFn() {
      const that = this;
      filterYarnColor({
        color: that.checkData.colorName
      }, data => {
        data.forEach(color => {
          that.actionSheetData.push({
            name: color
          });
        });
        that.showActionSheet = true;
      })
    },
    /* 筛选批次 */
    filterYarnBatchFn() {
      const that = this;
      listYarnBatchByYarn({
        yarnId: that.checkData.yarnId
      }, data => {
        data.forEach(batch => {
          that.actionSheetData.push({
            name: batch.no + SPLIT_ZKH + "预计库存:" + batch.expectStock + ", 库存:" + batch.stock + SPLIT_YKH,
            item: batch
          });
        });
        that.showActionSheet = true;
      });
    },
    /* 筛选区域 */
    filterYarnStoreAreaFn() {
      const that = this;
      getByType({
        pageSize: 1000,
        type: 9,
      }, res => {
        res.list.forEach((item) => {
          that.actionSheetData.push({
            name: item.propertyValue,
          });
        });
        that.showActionSheet = true;
      });
    },
    /* 筛选盘库 */
    filterYarnCheckFn() {
      const that = this;
      filterYarnCheckData({
        yarnNo: that.queryParam.yarnNo
      }, data => {
        data.forEach(check => {
          that.actionSheetData.push({
            name: check.no,
            subname: check.createAt.substring(0, 10) + SPLIT_XHX + check.stockArea + SPLIT_XHX + check.stock,
            item: check
          });
        });
        that.showActionSheet = true;
      });
    },

    /* 选择数据 */
    selectFilterDataFn(action) {
      const that = this;
      if (1 == that.queryParam.optFlag) {
        that.selectYarnDataFn(action);
      } else if (2 == that.queryParam.optFlag) {
        that.selectYarnColorFn(action);
      } else if (3 == that.queryParam.optFlag) {
        that.selectYarnBatchFn(action);
      } else if (4 == that.queryParam.optFlag) {
        that.selectYarnStoreAreaFn(action);
      } else if (5 == that.queryParam.optFlag) {
        that.selectYarnCheckFn(action);
      }
    },
    /* 选择纱线 */
    selectYarnDataFn(action) {
      const that = this;
      that.checkData.yarnId = action.item.id;
      that.checkData.no = action.item.no;
      that.checkData.colorName = action.item.colorName;
      that.checkData.standard = parseFloat(action.item.standard) + SPLIT_XG + action.item.strandNum;
      that.filterDataFn(3, 100);
    },
    /* 选择颜色 */
    selectYarnColorFn(action) {
      const that = this;
      that.checkData.colorName = action.name;
    },
    /* 选择批次 */
    selectYarnBatchFn(action) {
      const that = this;
      that.checkData.batchId = action.item.id;
      that.checkData.lotNum = action.item.no;
    },
    /* 选择区域 */
    selectYarnStoreAreaFn(action) {
      const that = this;
      that.checkData.stockArea = action.name;
    },
    /* 选择盘库记录 */
    selectYarnCheckFn(action) {
      const that = this;
      console.log(action);
      Object.keys(that.checkData).forEach(key => {
        that.checkData[key] = action.item[key];
      });
    },

    /* 校验 */
    validatorFn(val, rule) {
      const that = this;
      let result = val != "";
      if(!result) {
        that.$toast.fail(rule.message);
      }
      return result;
    },

    /* 确认盘库 */
    confirmCheckFn() {
      const that = this;
      that.checkData.id = 0;    //置0
      confirmYarnCheck(that.checkData, data => {
        that.$toast.success("确认成功");
        that.checkData.id = data.id;
        that.checkData.checkerName = getInfo().realName;
        that.printLabel(data);
      });
    },

    /* 重新打印 */
    rePrintFn() {
      const that = this;
      if(that.checkData.id > 0) {
        that.printLabel(that.checkData);
      }
    },

    /* 判断蓝牙是否打开 */
    isEnabledBluetooth() {
      const that = this;
      window.api.require("cxgBluetoothBase").isEnabledBluetooth({}, (ret, err) => {
        if (!err) {
          if (ret.state) {
            // 已打开
            that.connectBleByMacAddress();
          } else {
            that.openBluetooth();
          }
        } else {
          that.$toast.fail("code: " + err.code + " msg: " + err.msg);
        }
      });
    },
    /* 打开蓝牙 */
    openBluetooth() {
      const that = this;
      window.api.require("cxgBluetoothBase").openBluetooth({}, function (ret, err) {
        if (!err) {
          if (ret.state) {
            // 已打开
            that.connectBleByMacAddress();
          }
        } else {
          that.listenBluetoothStatus();
        }
      });
    },
    /* 监听蓝牙连接状态 */
    listenBluetoothStatus() {
      const that = this;
      window.api.require("cxgBluetoothBase").listenBluetoothStatus({}, function (ret, err) {
        if (!err) {
          if (ret.status === "STATE_ON") {
            that.connectBleByMacAddress();
          }
        } else {
          that.$toast.fail("code: " + err.code + " msg: " + err.msg);
        }
      });
    },
    // 查询打印机连接状态
    getConnectState() {
      const that = this;
      that.$toast({
        message: "正在打印",
        type: "loading",
        duration: 20000,
      });
      let obj = window.api.require("xGprinterPlus");
      let ret = obj.getConnectState();
      if (ret.status) {
        let result = false;
        ret.state.forEach((bool) => {
          if (bool) {
            result = bool;
          }
        });
        if (result) {
          // 已连接
          that.$toast.clear();
        } else {
          // 未连接
          that.$toast({
            type: "fail",
            message: "未连接, 请等待",
            duration: 1500,
            onClose: () => {
              that.connectBleByMacAddress();
            },
          });
        }
      } else {
        // 未连接
        that.$toast({
          type: "fail",
          message: "未连接, 请等待",
          duration: 1500,
          onClose: () => {
            that.connectBleByMacAddress();
          },
        });
      }
    },
    /* 连接蓝牙 */
    connectBleByMacAddress(status) {
      const that = this;
      if (that.printStatus) {
        that.$toast({
          message: "初始化打印机",
          type: "loading",
          duration: 20000,
        });
      }
      let demo = window.api.require("xGprinterPlus");
      demo.connectBleByMacAddress({
        macAddress:  getMacAddress() ? getMacAddress().address : '',
      }, (ret, err) => {
        if (ret.status) {
          if (ret.message === "已连接") {
            that.connectionStatus = true;
            if (that.printStatus) {
              that.$toast({
                type: "success",
                message: "连接成功",
                duration: 1500,
              });
            }
            if (status) {
              // that.onClickAddStore();    //新增盘库?
            }
          } else if (ret.message === "连接失败") {
            that.connectionStatus = false;
            that.$toast({
              type: "fail",
              message: "初始化失败",
              duration: 1500,
            });
          } else {
            that.connectionStatus = false;
          }
        } else {
          that.$toast({
            type: "fail",
            message: err.msg,
            duration: 1500,
          });
        }
      });
    },

    /* 打印数据 */
    printLabel(checkData) {
      const that = this;
      let obj = window.api.require("xGprinterPlus");
      let rows = [{
        lineType: "size",
        width: 50,
        height: 70,
      }, {
        lineType: "gap",
        data: 3,
      }, {
        lineType: "cls",
      }, {
        // 图片单元格竖线
        lineType: "bar",
        x: 25 + 130,
        y: 0,
        width: 2,
        height: 136,
      }, {
        //绘制图片
        lineType: "image",
        x: 25 + 8,
        y: 8,
        data: "widget://image/huibo_logo.png",
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 8,
        y: 10,
        rotation: 0,
        xscal: 1,
        yscal: 1,
        data: "艺多染整",
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 8,
        y: 60,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "纱线盘库",
      }, {
        lineType: "qrcode", // 绘制qrcode
        x: 25 + 170 + 2,
        y: 10,
        level: "L", //L|M|H|Q
        cellwith: 5,
        rotation: 0, // 0|90|180|270
        data: "28," + checkData.id,
      }, {
        // 横线
        lineType: "bar",
        x: 25 + 4,
        y: 136,
        width: 156,
        height: 2,
      },/* {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 136 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: dayjs().format("YYYY-MM-DD"),
      }, */{
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 136 + 2,
        rotation: 0,
        xscal: 2,
        yscal: 2,
        data: "批次号:" + checkData.lotNum,
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 186,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 186 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "编号: " + checkData.no,
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 236,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 236 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "区域:" + checkData.stockArea,
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 286,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 286 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "颜色: " + checkData.colorName,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 336 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "规格: " + checkData.standard,
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 336,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 386 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "重量: " + checkData.stock + "KG",
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 386,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 436 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "操作人: " + checkData.checkerName,
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 436,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 516 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 1,
        data: "盘库日期: " + dayjs().format("YYYY-MM-DD"),
      },];
      obj.printLabel({
        rows: rows,
      }, (ret, err) => {
        if (ret.status) {
          that.$toast.success("打印成功");
          --that.printCount;
          if (that.printCount > 0) {
            that.printLabel(checkData);
          } else {
            that.printCount = 1;
          }
        } else {
          that.$toast({
            type: "fail",
            message: err.code + err.msg,
            duration: 1500,
            onClose: () => {
              that.connectBleByMacAddress();
            },
          });
        }
      });
    },
  }
}
</script>

<style lang="scss" scoped>
.yarn-check {
  ::v-deep .van-search {
    z-index: 1;
  }
}
</style>